import {
  baseURL
} from '../config.js';
const request = ({
  url,
  method,
  params,
  headers
}) => {
  let serachUrl = url;
  let data = null;
  if (method === 'GET' && params) {
    const keys = Object.keys(params);
    keys.forEach((k, i) => {
      const query = `${k}=${encodeURIComponent(params[k])}`;
      const linkSymbol = i === 0 ? '?' : '&';
      serachUrl = `${serachUrl}${linkSymbol}${query}`;
    });
  } else if ((method === 'POST') && params) {
    data = JSON.stringify(params);
  }
  let headersConfig = {
    'Content-Type': 'application/json'
  };
  if (headers) {
    headersConfig = {
      ...headersConfig,
      ...headers,
    };
  }
  return new Promise((resolve, reject) => {
    const config = {
      headers: headersConfig,
      method,
      url: `${baseURL}${serachUrl}`,
      dataType: 'json',
      success: (res) => {
        resolve(res);
      },
      fail: (res) => {
        reject(res);
      }
    };
    if (data) {
      config.data = data;
    }
    dd.httpRequest(config);
  });
};
export default request;